<template>
  <div class="addressContainer">
    <van-form @submit="onSubmit" class="van-address-edit">
      <van-field
        v-model="userName"
        name="收货人"
        label="收货人"
        placeholder="收货人姓名"
        :rules="[{ required: true, message: '请填写收货人姓名' }]"
      />

      <van-field
        v-model="phone"
        name="手机号"
        label="手机号"
        placeholder="收货人手机号"
        type="tel"
        :rules="[{ required: true, message: '请填写收货人手机号' }]"
      />
      <van-field @click="selectCity(1)"
        v-model="jsonValue"
        name="所在地区"
        label="所在地区"
        placeholder="省市区"
        :readonly="true"
        :rules="[{ required: true, message: '请选择省市区' }]"
      >
      <template #button>
        <van-icon class="position" size="16" :name="position" />位置
      </template>
      </van-field>
      <van-field
      class="textraBox"
        v-model="address"
        rows="2"
        autosize
        label="详细地址"
        type="textarea"
        placeholder="如街道、门牌号、小区、楼栋 号、单元室"
        show-word-limit
        :rules="[{ required: true, message: '请输入详细地址' }]"
      />
    <van-checkbox-group v-model="result" class="defChecked">
      <van-cell-group>
        <van-cell
          clickable
          title="设为默认收货地址"
          @click="setToggle(checked)"
        >
          <template #right-icon>
            <van-checkbox checked-color="#ee0a24" ref="checkboxes" />
          </template>
        </van-cell>
      </van-cell-group>
    </van-checkbox-group>

      <div class="van-buttons">
        <van-button native-type="submit" type="primary" size="28" color="#DB1919" block>保存</van-button>
      </div>
    </van-form>

    <van-action-sheet
      class="cityPopupBox"
      v-model="diaogCityShow"
      title="选择所在地"
    >
      <div class="custom-indicator layout-box">
        <div class="cityTexts" @click="onClosed1" v-if="currProvince!=''">{{ currProvince.areaName }}<van-icon :name="closed" /></div>
        <div class="citySteps" v-if="currProvince!=''" :class="currCity != ''?'on':''">
          <div class="l-rs"></div>
          <div class="c-rs"></div>
          <div class="r-rs"></div>
        </div>
        <div class="cityTexts" @click="onClosed2" v-if="currCity != ''">{{ currCity.areaName }}<van-icon :name="closed" /></div>
        <div class="citySteps" v-if="currCity!=''" :class="currRegion != ''?'on':''">
          <div class="l-rs"></div>
          <div class="c-rs"></div>
          <div class="r-rs"></div>
        </div>
        <div class="cityTexts" @click="onClosed3" v-if="currRegion!=''">{{ currRegion.areaName }}<van-icon :name="closed" /></div>
      </div>
      <van-index-bar class="indexBar" :sticky="false" highlight-color="#fb6463">
        <div v-if="provinceShow">
          <van-index-anchor
            v-for="(item, index) in provinceName"
            :key="index"
            v-if="item.length > 0"
          >
            <div class="layout-box">
              <span class="indexWord">{{ index }}</span>
              <div class="box-col">
                <van-cell
                  @click="chooseProvince(citem,cindex)"
                  v-for="(citem, cindex) in item"
                  :key="cindex"
                  :title="citem.areaName"
                  :class="currIndex === citem.id?'on':''">
                  <template #right-icon v-if="currIndex === citem.id">
                    <van-checkbox v-model="cityModel" checked-color="#ee0a24" ref="checkboxes" />
                  </template>
                </van-cell>
              </div>
            </div>
          </van-index-anchor>
        </div>
        <div v-if="cityShow">
          <van-index-anchor
            v-for="(item, index) in cityName"
            :key="index"
            v-if="item.length > 0"
          >
            <div class="layout-box">
              <span class="indexWord">{{ index }}</span>
              <div class="box-col">
                <van-cell
                  @click="chooseCity(citem)"
                  v-for="(citem, cindex) in item"
                  :key="cindex"
                  :title="citem.areaName"
                  :class="currIndex === citem.id?'on':''"
                />
              </div>
            </div>
          </van-index-anchor>
        </div>
        <div v-if="regionShow">
          <van-index-anchor
            v-for="(item, index) in regionName"
            :key="index"
            v-if="item.length > 0"
          >
            <div class="layout-box">
              <span class="indexWord">{{ index }}</span>
              <div class="box-col">
                <van-cell
                  @click="chooseRegion(citem)"
                  v-for="(citem, cindex) in item"
                  :key="cindex"
                  :title="citem.areaName"
                  :class="currIndex === citem.id?'on':''">
                </van-cell>
              </div>
            </div>
          </van-index-anchor>
        </div>
      </van-index-bar>
    </van-action-sheet>
  </div>
</template>

<script>
import $api from "@/api/index";
/*
import province from "./province.json";
import city from "./city.json";
import region from "./region.json";
*/
import pinyin from "js-pinyin";
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  // import引入的组件需要注入到对象中才能使用
  name: "",
  components: {},
  data() {
    // 这里存放数据
    return {
      position:require('@/assets/icon/icon-position.png'),
      closed:require('@/assets/icon/icon-closed.png'),
      addressId:'',
      eidtType:'0',
      currIndex:110000,
      cityModel:true,
      checked:false,
      result: [],
      diaogCityShow: false,
      provinceList: [],
      FirstPin: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "J",
        "K",
        "L",
        "M",
        "N",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "W",
        "X",
        "Y",
        "Z",
      ],
      provinceName: [],
      cityName: [],
      regionName: [],
      currProvince: "",
      currCity: "",
      currRegion: "",
      provinceShow: true,
      cityShow: false,
      regionShow: false,
      jsonValue:'',
      userName:'',
      phone:'',
      address:''
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    getAddress() {
      let router = this.$route.query
      if(router.type){
        let types = JSON.parse(router.type)
        this.eidtType = types
        this.addressId = router.addressId
        if(types == 1){
          let params = {
            addressId:router.addressId
          }
          $api.shopApi.detailAddress(params).then((res)=>{
            if(res.status == 10000){
              let data = res.data
              this.currProvince = {areaName:data.area.provinceName,id:data.province}
              this.currCity = {areaName:data.area.cityName,id:data.city}
              this.currRegion = {areaName:data.area.regionName,id:data.region}
              this.userName = data.userName
              this.phone = data.phone
              this.address = data.address
              this.defaultAddress = data.defaultAddress
              this.jsonValue = data.area.provinceName + data.area.cityName + data.area.regionName
              if(data.defaultAddress == true){
                this.checked = true
                this.$refs.checkboxes.toggle();
              }
            }
          })
        }
      }
    },
    onSubmit(){
      let params = {
        address:this.address,
        city:this.currCity.id,
        defaultAddress:this.checked,
        phone:this.phone,
        province:this.currProvince.id,
        region:this.currRegion.id,
        userName:this.userName
      }
      if(this.eidtType == 1){
        params.addressId = this.addressId
        $api.shopApi.editAddress(params).then((res)=>{
          if(res.status == 10000){
            this.$toast("编辑成功");
            this.$router.go(-1)
            //this.$router.push({path:"/myAddress"})
          }
        })
      }else{
        $api.shopApi.createAddress(params).then((res)=>{
          console.log(res)
          if(res.status == 10000){
            this.$toast("新增成功");
            this.$router.go(-1)
            //this.$router.push({path:"/myAddress"})
          }
        })
      }
    },
    setToggle(index) {
      this.$refs.checkboxes.toggle();
      this.checked = !this.checked
    },
    getCity(parentId,index){
      let vm = this
      let params = {
        parentId:parentId
      }
      $api.shopApi.excludeAreas(params).then((res)=>{
        console.log(res.data)
        if(res.status == 10000){
          this.provinceList = res.data
          this.diaogCityShow = true;
          let pinyin = require("js-pinyin");
          pinyin.setOptions({ checkPolyphone: false, charCase: 0 });
          let list = [];
          let dataList = [];
          let name = {};
          dataList = this.provinceList;
          for (let p in dataList) {
            list.push(dataList[p]);
          }
          this.FirstPin.forEach((item) => {
            name[item] = [];
            list.forEach((el) => {
              let first = pinyin.getFullChars(el.areaName).substring(0, 1);
              if (first == item) {
                name[item].push(el);
              }
            });
          });
          if (index == 1) {
            this.provinceName = name;
            this.provinceShow = true;
            this.cityShow = false;
            this.regionShow = false;
            this.currIndex = this.currProvince.id
          } else if (index == 2) {
            this.cityName = name;
            this.provinceShow = false;
            this.cityShow = true;
            this.regionShow = false;
            this.currIndex = this.currCity.id
            //this.currProvince = ''
            this.currCity = ''
            this.currRegion = ''
          } else {
            this.regionName = name;
            this.provinceShow = false;
            this.cityShow = false;
            this.regionShow = true;
            this.currIndex = this.currRegion.id
          }
        }else{
          this.$toast('查询出错了')
        }
      })
    },
    selectCity(index) {
      let vm = this
      if (index == 1) {
        this.getCity('0',index)
      } else if (index == 2) {
        this.getCity(vm.currIndex,index)
      } else if (index == 3) {
        this.getCity(vm.currIndex,index)
      }
    },
    chooseProvince(item) {
      this.currProvince = item;
      this.currIndex = item.id
      this.selectCity(2);
    },
    chooseCity(item) {
      this.currCity = item;
      this.currIndex = item.id
      this.selectCity(3);
    },
    chooseRegion(item) {
      this.currIndex = item.id
      this.currRegion = item;
      this.diaogCityShow = false
      this.jsonValue = this.currProvince.areaName + this.currCity.areaName + this.currRegion.areaName
    },
    onClosed1(){
      this.currProvince = ''
      this.currCity = ''
      this.currRegion = ''
      this.currIndex = ''
      this.selectCity(1);
    },
    onClosed2(){
      this.currIndex = this.currProvince.id
      this.currCity = ''
      this.currRegion = ''
      this.selectCity(2);
    },
    onClosed3(){
      this.currIndex = this.currCity.id
      this.currRegion = ''
      this.selectCity(3);
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getAddress()
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss'>
// @import url(); 引入公共css类
.addressContainer{
  background: #f2f5f4;
  height: 100vh;
  overflow-x: auto;
  .van-field__body{
    .van-field__control{
      &::placeholder{
      color: #333333 !important;
      }
    }
  }
  .van-field__error-message{
    display: none;
  }
  .van-field__label{
    width: 160px;
  }
  .van-address-edit{
    padding: 0;
  }
  .defChecked{
    margin-top: 24px;
  }
  .van-buttons{
    padding: 96px 24px 24px;
  }
  .van-address-edit-detail{
    padding-bottom: 80px;
    textarea{
      width: 80%;
    }
  }
  .position{
    margin-right:5px;
  }
  .textraBox{
    padding-bottom: 100px;
    .van-field__body{
      width: 80%;
    }
  }
}


.defChecked{
  text-align: left;
  position: relative;
  .van-checkbox__icon{
    position: absolute;
    right: 24px;
  }
  .van-checkbox__label{
    margin: 0;
  }
}
</style>
